const BASE_URL = 'http://localhost:8000/api';  // 开发环境可以是本地IP

// 请求封装
const request = (url, method, data, needToken = true) => {
  return new Promise((resolve, reject) => {
    const header = {
      'Content-Type': 'application/json'
    };
    
    // 如果需要认证，添加token
    if (needToken) {
      const token = wx.getStorageSync('token');
      if (token) {
        header['Authorization'] = `Bearer ${token}`;
      }
    }
    
    wx.request({
      url: `${BASE_URL}${url}`,
      method,
      data,
      header,
      success: (res) => {
        if (res.statusCode === 401) {
          // token失效，重新登录
          wx.removeStorageSync('token');
          wx.reLaunch({
            url: '/pages/login/login'
          });
          reject(new Error('登录已过期，请重新登录'));
          return;
        }
        
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

// API函数
const api = {
  // 登录
  login: (code) => {
    return request('/auth/login', 'POST', { code }, false);
  },
  
  // 更新用户信息
  updateUserInfo: (userInfo) => {
    return request('/auth/user-info', 'POST', {
      nickname: userInfo.nickName,
      avatar_url: userInfo.avatarUrl
    });
  },
  
  // 获取用户资料
  getUserProfile: () => {
    return request('/user/profile', 'GET');
  },
  
  // 保存手机号
  savePhoneNumber: (phoneNumber) => {
    return request('/car-owner/phone', 'POST', { phone_number: phoneNumber });
  },
  
  // 获取挪车码
  getQrCode: () => {
    return request('/car-owner/qrcode', 'GET');
  },
  
  // 解析扫描的二维码
  decodeQrCode: (qrData) => {
    return request('/scan/decode', 'POST', { qr_data: qrData });
  },
  
  // 记录拨打电话
  logCallMade: (carOwnerId) => {
    return request('/scan/call-log', 'POST', { car_owner_id: carOwnerId });
  }
};

module.exports = {
  api
}; 